import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/routes/routes.dart';
import 'package:provider/provider.dart';

import 'forget_pwd_request.dart';

class FoundPwdPage extends StatefulWidget {
  @override
  _FoundPwdPageState createState() => _FoundPwdPageState();
}

class _FoundPwdPageState extends State<FoundPwdPage> {
  Timer _countdownTimer;
  String _codeCountdownStr = '获取验证码';
  int _countdownNum = 59;

  //焦点
  FocusNode _focusNodeUserPhone = new FocusNode();
  FocusNode _focusCode = new FocusNode();

  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userPhoneController = new TextEditingController();
  TextEditingController _userCodeController = new TextEditingController();

//  GlobalKey _formKey= new GlobalKey<FormState>();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  var _isShowClear = false; //是否显示输入框尾部的
  var _isShowClearCode = false; //是否显示输入框尾部的
  @override
  void initState() {
    //设置焦点监听
    _focusNodeUserPhone.addListener(_focusNodeListener);
    _focusCode.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userPhoneController.addListener(() {
      print(_userPhoneController.text);
      errormobile = null;

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _userCodeController.addListener(() {
      print(_userCodeController.text);
      errorcode = null;

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userCodeController.text.length > 0) {
        _isShowClearCode = true;
      } else {
        _isShowClearCode = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodeUserPhone.removeListener(_focusNodeListener);
    _focusCode.removeListener(_focusNodeListener);
    _userPhoneController.dispose();
    _userCodeController.dispose();
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodeUserPhone.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
      _focusCode.unfocus();
    }
    if (_focusCode.hasFocus) {
      print("密码框获取焦点");
      (_formKey.currentState as FormState).reset();

      // 取消用户名框焦点状态
      _focusNodeUserPhone.unfocus();
      errormobile = validateUserPhone(_userPhoneController.text);
    }
  }

  /**
   * 验证用户名
   */
  String validateUserPhone(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (value.isEmpty) {
      return '用户名不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    } else if (_userPhoneController.text.length != 11) {
      return '请输入格式正确的手机号';
    }
    return null;
  }

  /**
   * 验证密码
   */
  String validateCode(value) {
    if (value.isEmpty) {
      return '验证码不能为空';
    }
    return null;
  }

  var errormobile;
  var errorcode;

  @override
  Widget build(BuildContext context) {
    return ListenableProvider<ForgetPwdViewModel>(
        create: (_) {
          ForgetPwdViewModel model = ForgetPwdViewModel();
          return model;
        },
        child: Builder(
            builder: (context) => Scaffold(
                  appBar: AppBar(
                    centerTitle: true,
                    title: Text(
                      "找回登录密码",
                      style:
                          TextStyle(fontSize: 32.sp, color: Color(0xFF000000)),
                    ),
                    backgroundColor: Colors.white,
                    elevation: 0,
                    leading: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        Navigator.of(context).pushNamed(Routes.login_page);
                      },
                      child: Icon(
                        Icons.arrow_back_ios,
                        color: Color(0xFF000000),
                      ),
                    ),
                  ),
                  body: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onPanStart: (_) {
                        FocusScope.of(context).requestFocus(FocusNode());
                      },
                      child: Stack(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.fromLTRB(94.w, 153.h, 94.w, 0),
                            child: Form(
                              key: _formKey,
                              child: Column(
                                children: <Widget>[
                                  new TextFormField(
                                    style: TextStyle(color: Colors.black),
                                    controller: _userPhoneController,
                                    focusNode: _focusNodeUserPhone,
                                    //设置键盘类型
                                    keyboardType: TextInputType.number,
                                    inputFormatters: [
                                      WhitelistingTextInputFormatter.digitsOnly,
                                      //限制只允许输入数字
                                      LengthLimitingTextInputFormatter(11),
                                      //限制输入长度不超过8位
                                    ],
                                    decoration: InputDecoration(
                                      errorText: errormobile,

                                      errorStyle: TextStyle(
                                          color: Color(0xFFFE0600),
                                          fontSize: 20.sp),
                                      hintText: "手机号 (请输入11位手机号)",
                                      hintStyle: TextStyle(
                                          fontSize: 28.sp,
                                          color: Color(0xFF999999)),
//                        尾部添加清除按钮
                                      suffixIcon: (_isShowClear)
                                          ? IconButton(
                                              icon: Icon(
                                                Icons.cancel,
                                                size: 27.sp,
                                              ),
                                              onPressed: () {
                                                // 清空输入框内容
                                                _userPhoneController.clear();
                                              },
                                            )
                                          : null,
                                    ),
                                    validator: validateUserPhone,
                                  ),
                                  Text(
                                    "",
                                    style: TextStyle(fontSize: 10.sp),
                                  ),
                                  new TextFormField(
                                      style: TextStyle(
                                          color: Color(0xFF000000),
                                          fontSize: 28.sp),
                                      controller: _userCodeController,
                                      focusNode: _focusCode,
                                      inputFormatters: [
//                    WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")),      //限制只允许输入字母和数字
                                        WhitelistingTextInputFormatter
                                            .digitsOnly,
                                        //限制只允许输入数字
                                        LengthLimitingTextInputFormatter(6),
                                        //限制输入长度不超过8位
                                      ],
                                      keyboardType: TextInputType.number,
                                      decoration: InputDecoration(
                                        errorText: errorcode,
                                        errorStyle: TextStyle(
                                            color: Color(0xFFFE0600),
                                            fontSize: 20.sp),
                                        suffixIcon: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: <Widget>[
                                            (_isShowClearCode)
                                                ? IconButton(
                                                    icon: Icon(
                                                      Icons.cancel,
                                                      size: 27.sp,
                                                    ),
                                                    onPressed: () {
                                                      // 清空输入框内容
                                                      _userCodeController
                                                          .clear();
                                                    },
                                                  )
                                                : Text(""),
                                            Builder(
                                                builder: (context) =>
                                                    FlatButton(
                                                      onPressed:
                                                          _countdownNum == 59
                                                              ? () {
                                                                  context.read<ForgetPwdViewModel>().code(
                                                                      _userPhoneController
                                                                          .text,
                                                                      "3",
                                                                      onSuccess:
                                                                          () {
                                                                    reGetCountdown();
                                                                  }, onFail:
                                                                          (error) {
                                                                    decideError(
                                                                        error);
                                                                  });
                                                                }
                                                              : null,
                                                      child: Text(
                                                        _codeCountdownStr,
                                                        style: TextStyle(
                                                            fontSize: 31.sp,
                                                            color:
                                                                Color.fromRGBO(
                                                                    130,
                                                                    134,
                                                                    142,
                                                                    1)),
                                                      ),
                                                    ))
                                          ],
                                        ),
                                        hintText: "请输入验证码",
                                        hintStyle: TextStyle(
                                            fontSize: 28.sp,
                                            color: Color(0xFF999999)),
                                        counter: InkWell(
                                          child: Text(
                                            "收不到验证码？",
                                            style: TextStyle(
                                                fontSize: 20.sp,
                                                color: Color(0xFF82868E)),
                                          ),
                                          onTap: () {
                                            Navigator.pop(context);

                                            Navigator.of(context)
                                                .pushNamed(Routes.prompt);
                                          },
                                        ),
                                      ),
                                      //验证码验证
                                      validator: validateCode),
                                ],
                              ),
                            ),
                          ),
                          Positioned(
                            left: 94.w,
                            top: 718.h,
                            child: Container(
                              width: 560.w,
                              height: 80.h,
                              color: Color(0xFFE2E5EA),
                              child: new FlatButton(
                                  highlightColor: Color(0xFF0CABCB),
                                  child: new Text(
                                    '下一步',
                                    style: TextStyle(
                                        fontSize: 30.sp,
                                        color: Color(0xFFFFFFFF)),
                                  ),
                                  onPressed: () {
                                    if ((_formKey.currentState).validate()) {
                                      context.read<ForgetPwdViewModel>().vacode(
                                          _userPhoneController.text,
                                          "3",
                                          _userCodeController.text,
                                          onSuccess: () {
                                        Navigator.pop(context);
                                        Navigator.of(context).pushNamed(
                                            Routes.forgetpwd,
                                            arguments: {
                                              "mobile":
                                                  _userPhoneController.text,
                                              "code": _userCodeController.text,
                                            });
                                      }, onFail: (error) {
                                        decideError(error);
                                        _focusNodeUserPhone.unfocus();
                                        _focusCode.unfocus();
                                      });
                                    } else {
                                      _focusNodeUserPhone.unfocus();
                                      _focusCode.unfocus();
                                    }
                                  }),
                            ),
                          ),
                        ],
                      )),
                )));
  }

  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
      _codeCountdownStr = '${_countdownNum--}s后重新获取';
      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _codeCountdownStr = '${_countdownNum--}s后重新获取';
          } else {
            _codeCountdownStr = '获取验证码';
            _countdownNum = 59;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  void decideError(String T) {
    setState(() {
      if (T.length > 10) {
        errormobile = T;
      } else if (T.length < 10) {
        errorcode = T;
      }
    });
  }

  void send() {
    context.read<ForgetPwdViewModel>().code(_userPhoneController.text, "3",
        onSuccess: () {
      reGetCountdown();
    }, onFail: (error) {
      decideError(error);
    });
  }

  bool sendCode() {
    if (validateUserPhone(_userPhoneController.text) == null &&
        _countdownNum == 59) {
      return true;
    } else {
      errormobile = validateUserPhone(_userPhoneController.text);
      return false;
    }
  }
}
